package com.smalls.redshoes.ui.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.smalls.newvideotwo.base.BaseActivity;
import com.smalls.newvideotwo.db.Links;
import com.smalls.newvideotwo.db.Record;
import com.smalls.newvideotwo.db.VodDao;
import com.smalls.newvideotwo.mvp.bean.MovieDetail;
import com.smalls.newvideotwo.mvp.bean.StreamInfo;
import com.smalls.newvideotwo.util.LogUtil;
import com.smalls.newvideotwo.utils.Constant;
import com.smalls.newvideotwo.utils.Utils;
import com.smalls.newvideotwo.view.BaseDialog;
import com.smalls.redshoes.R;
import com.smalls.redshoes.ui.widget.AccelerationSeekBar;
import com.smalls.redshoes.ui.widget.PlayBarSelectVodLayout;
import com.smalls.redshoes.ui.widget.VodPlayControlBottomView;
import com.smalls.redshoes.ui.widget.VodPlayControlView;
import com.smalls.redshoes.util.DateUtil;
import com.smalls.redshoes.util.SPUtil;
import com.uking.moudle.UKingPlayerIJKImpl;
import com.uking.udppush.UKingPlayerMessageService;
import com.uking.util.VKConstant;

import java.util.ArrayList;
import java.util.List;

public class VodPlayActivity extends BaseActivity {
    private static String TAG = Constant.baddcoolio2tag?Constant.TAGPREFIXSTR + VodPlayActivity.class.getSimpleName():VodPlayActivity.class.getSimpleName();
    private static final long DELAY_CHECK_ISPLAYING = 3000;
    public static final long DELAY_SET_CAN_SHOW_EC_ERROR = 35000;
    public static final String EXTRA_STREAMING_INDEX = "sets";
    public static final String EXTRA_VOD_DATA = "videoinfo";
    public static final int INVALID_JNI_ERROR_CODE = -1;
    public static final int MS_TO_S = 1000;
    public static final long PLAY_CONTINUE_COUNT_DOWN_INTERVAL = 1000;
    public static final long PLAY_CONTINUE_COUNT_DOWN_TIME = 6000;
    public static final int POP_JIN_ERROR_CODE_INTERVAL = 10000;
    public static final int RETRY_TIME_INTERVAL = 10000;
    private int beginCheckPosition = 0;
    private boolean canShowEcError = false;
    private Record album;
    private int offsetPlayOption = 20 * 1000;
    private long mStartMs = 0;

    protected ServiceConnection connection = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            ((UKingPlayerMessageService.MyBinder) service).getService().startUdpListener(getPort());
        }
    };
    private boolean hasRecordPlayPosition = false;
    protected boolean isBound = false;
    private boolean isPause = false;
    private boolean isPlayerError = false;
    private boolean isPrepared = false;
    private Handler VKJniHander = new Handler() {
        public void handleMessage(Message msg) {
            LogUtil.d(TAG, "VKJniHander.error=" + msg.what);
            if (msg.what != BaseImageDownloader.DEFAULT_HTTP_READ_TIMEOUT) {
                mJinErrorCode = msg.what;
                if (msg.what == VKConstant.ZHONGJJ_EXIT_ERROR) {
                    showErrorToastDialog(msg.what, false);
                } else if (SystemClock.uptimeMillis() - mLastSetTime >= 10000L && canShowEcError && !isPause) {
                    mLastSetTime = SystemClock.uptimeMillis();
                    startCheckPlaying();
                    LogUtil.d(TAG, "startCheckPlaying");
                }
            }
        }
    };
    private Handler mCheckPlayerIsPlayingHandler = new Handler();
    private Runnable mCheckPlayerIsPlayingRunnable = new Runnable() {
        public void run() {
            LogUtil.d(TAG, "mCheckPlayerIsPlayingRunnable");
            if (mUKingPlayerIJKImpl != null && mUKingPlayerIJKImpl.getMediaPlayer() != null) {
                long endCheckPosition = mUKingPlayerIJKImpl.getMediaPlayer().getCurrentPosition() / VodPlayActivity.MS_TO_S;
                LogUtil.d(TAG, "beginCheckPosition=" + beginCheckPosition + "  endCheckPosition=" + endCheckPosition);
                if ((beginCheckPosition >= 0 || endCheckPosition >= 0) && endCheckPosition > beginCheckPosition) {
                    cancelToastErrorDialog();
                    mCheckPlayerIsPlayingHandler.removeCallbacks(mCheckPlayerIsPlayingRunnable);
                    mJinErrorCode = VodPlayActivity.INVALID_JNI_ERROR_CODE;
                    return;
                }
                if (!(mJinErrorCode == VodPlayActivity.INVALID_JNI_ERROR_CODE || mJinErrorCode == getErrorCode())) {
                    showErrorToastDialog(mJinErrorCode, false);
                }
                startCheckPlaying();
            }
        }
    };
    private int mDuration;
    private int mJinErrorCode = INVALID_JNI_ERROR_CODE;
    private UKingPlayerIJKImpl mUKingPlayerIJKImpl;
    private Handler mUKingPlayerIJKImplHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UKingPlayerIJKImpl.PLAYER_PREPARING /*61696*/:
                    LogUtil.d(TAG, "PLAYER_PREPARING");
                    mPlayBar.setState(0);
                    return;
                case UKingPlayerIJKImpl.PLAYER_PREPARED /*61697*/:
                    LogUtil.d(TAG, "PLAYER_PREPARED");
                    setPlayerPrePared();
                    return;
                case UKingPlayerIJKImpl.PLAYER_BUFFERING_START /*61698*/:
                    LogUtil.d(TAG, "PLAYER_BUFFERING_START");
                    setPlayerBuffering();
                    return;
                case UKingPlayerIJKImpl.PLAYER_BUFFERING_END /*61699*/:
                    LogUtil.d(TAG, "PLAYER_BUFFERING_END");
                    setPlayerPlaying();
                    return;
                case UKingPlayerIJKImpl.PLAYER_ERROR /*61700*/:
                    LogUtil.d(TAG, "PLAYER_ERROR arg1=" + msg.arg1);
                    cancelErrorDialog();
                    if (msg.arg1 != -38) {
                        mPlayBar.setState(VodPlayActivity.INVALID_JNI_ERROR_CODE);
                        if (SystemClock.uptimeMillis() - mLastReTryTime >= 10000L) {
                            isPlayerError = true;
                            rePlay();
                            mLastReTryTime = SystemClock.uptimeMillis();
                            return;
                        }
                        return;
                    }
                    mPlayBar.setState(-2);
                    return;
                case UKingPlayerIJKImpl.PLAYER_SEEK_END /*61701*/:
                    LogUtil.d(TAG, "PLAYER_SEEK_END");
                    return;
                case UKingPlayerIJKImpl.PLAYER_PROGRESS_INFO /*61702*/:
                    updatePlayTime();
                    if (mUKingPlayerIJKImpl != null && mUKingPlayerIJKImpl.getMediaPlayer() != null) {
                        int currentPosition = (int)mUKingPlayerIJKImpl.getMediaPlayer().getCurrentPosition();
                        if (currentPosition > 0 && mLastPosition > 0 && mLastPosition < currentPosition && mPlayBar.getState() == 4) {
                            setPlayerPlaying();
                        }
                        mLastPosition = currentPosition;
                        return;
                    }
                    return;
                case UKingPlayerIJKImpl.PLAYER_COMPLETE /*61703*/:
                    LogUtil.d(TAG, "PLAYER_COMPLETE  code==" + msg.what);
                    clearPlayPosition();
                    setPlayerComplete();
                    return;
                default:
                    return;
            }
        }
    };
    private int mLastPosition = 0;
    private long mLastReTryTime = 0;
    private long mLastSetTime = 0;
    private VodPlayControlView.OnEventListener mOnPlaybarEventListener = new VodPlayControlView.OnEventListener() {
        public void onSeekedComplete(int progress) {
            if (mUKingPlayerIJKImpl != null && mUKingPlayerIJKImpl.getMediaPlayer() != null) {
                int progressTime = Math.abs((int) (((double) progress) * (((double) mDuration) / VodPlayControlBottomView.SEEKBAR_MAX_PROGRESS)));
                LogUtil.d(TAG, "onSeekedComplete=" + progressTime);
                if (progressTime >= 0) {
                    mUKingPlayerIJKImpl.seekTo(progressTime);
                }
            }
        }

        public void onProgressChanged(int progress) {
            if (mDuration > 0 && mPlayBar != null && mPlayBar.isSeeking() && progress >= 0) {
                mPlayBar.setHasPlayedTime(((long) ((int) (((double) progress) * (((double) mDuration) / VodPlayControlBottomView.SEEKBAR_MAX_PROGRESS)))) / VodPlayActivity.PLAY_CONTINUE_COUNT_DOWN_INTERVAL);
            }
        }

        public void onStartSeek() {
            if (isPause) {
                setResume();
            }
        }
    };
    private VodPlayControlView mPlayBar;
    private Button mPlayContinueBtn;
    private PlayContinueCountDownTimer mPlayContinueCountDownTimer;
    private BaseDialog mPlayContinueDialog;
    private int mRecordLastPlayPosition = 0;
    private PlayBarSelectVodLayout mSelectLayout;
    private VodDao mStreamingDao = new VodDao();
    private int mStreamingIndex = 0;
    private ArrayList<StreamInfo> mStreamingModels = null;
    private SurfaceView mSv;
    private MovieDetail mVodData;
    private Runnable setCanShowEcErrorRunnable = new Runnable() {
        public void run() {
            canShowEcError = true;
            if (mJinErrorCode != VodPlayActivity.INVALID_JNI_ERROR_CODE && VKJniHander != null) {
                VKJniHander.sendEmptyMessage(mJinErrorCode);
            }
        }
    };

    private class PlayContinueCountDownTimer extends CountDownTimer {
        public PlayContinueCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        public void onTick(long millisUntilFinished) {
            if (mPlayContinueBtn != null) {
                mPlayContinueBtn.setText(getString(R.string.play_continue) + "(" + (millisUntilFinished / VodPlayActivity.PLAY_CONTINUE_COUNT_DOWN_INTERVAL) + ")");
            }
        }

        public void onFinish() {
            if (mPlayContinueDialog != null && mPlayContinueDialog.isShowing()) {
                setRecordContinuePlay();
                cancelPlayContinueDialog();
            }
        }
    }

    public int onSetContentView() {
        return R.layout.rs_activity_play;
    }

    protected void getIntentData() {
        mVodData = (MovieDetail) getIntent().getSerializableExtra(EXTRA_VOD_DATA);
        mStreamingIndex = getIntent().getIntExtra(EXTRA_STREAMING_INDEX, 0);
        if (mVodData != null && mVodData.getStreaming() != null && mVodData.getStreaming().size() > 0) {
            mStreamingModels = (ArrayList<StreamInfo>)mVodData.getStreaming();
        }
    }

    protected void initView(Bundle savedInstanceState) {
        mSv = (SurfaceView) findViewById(R.id.activity_play_sv);
        mPlayBar = (VodPlayControlView) findViewById(R.id.activity_play_control_panel);
        mSelectLayout = (PlayBarSelectVodLayout) findViewById(R.id.activity_vod_play_select_bar);
        if (mStreamingModels == null) {
            return;
        }
        if (mStreamingModels.size() > 1) {
            mPlayBar.getMenuHintView().setVisibility(View.VISIBLE);
        } else {
            mPlayBar.getMenuHintView().setVisibility(View.GONE);
        }
    }

    protected void setListener() {
        mSelectLayout.setOnStreamingClickedListener(new PlayBarSelectVodLayout.OnStreamingClickedListener() {
            public void onStreamingClicked(int position) {
                SPUtil.putInt(getApplicationContext(), mVodData.getMedia_code(), position);
                mStreamingIndex = position;
                loadAnother();
            }
        });
        mPlayBar.setOnEventListener(mOnPlaybarEventListener);
    }

    private void loadAnother() {
        mPlayBar.setState(0);
        LogUtil.d(TAG, "loadAnother");
        checkIsNeedPlayContinue();
    }

    protected void processLogic(Bundle savedInstanceState) {
        getIntentData();
        if (mStreamingModels == null || mStreamingModels.size() <= 0) {
            mPlayBar.setState(-2);
            return;
        }
        mSelectLayout.setDatas(mStreamingModels);
        init();
        checkIsNeedPlayContinue();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startFloatService();
        bindKBPlayerMsgServer();
    }

    public void clearResouse() {
        if (mPlayBar != null) {
            mPlayBar.destory();
        }
        if (this.mUKingPlayerIJKImpl != null) {
            this.mUKingPlayerIJKImpl.stop();
            this.mUKingPlayerIJKImpl.close();
        }
    }


    @Override
    protected void onDestroy() {
        clearResouse();
        stopFloatService();
        unBindKBPlayerMsgServer();
        super.onDestroy();
    }

    public void setTotalTime() {
        if (mUKingPlayerIJKImpl != null && mUKingPlayerIJKImpl.getMediaPlayer() != null) {
            mDuration = (int)mUKingPlayerIJKImpl.getMediaPlayer().getDuration();
            if (mDuration > 0 && mPlayBar != null) {
                mPlayBar.setTotalTime(mDuration / MS_TO_S);
                if (mPlayBar.getSeekBar() instanceof AccelerationSeekBar) {
                    ((AccelerationSeekBar) mPlayBar.getSeekBar()).setDuration(mDuration);
                }
            }
        }
    }

    public void updatePlayTime() {
        if (mUKingPlayerIJKImpl != null && mUKingPlayerIJKImpl.getMediaPlayer() != null && !mPlayBar.isSeeking()) {
            int mCurrPosition = (int)mUKingPlayerIJKImpl.getMediaPlayer().getCurrentPosition();
            if (mCurrPosition > 0 && mPlayBar != null) {
                mPlayBar.setHasPlayedTime((long) (mCurrPosition / MS_TO_S));
            }
            if (mDuration > 0) {
                int progress = (int) (((double) mCurrPosition) * (VodPlayControlBottomView.SEEKBAR_MAX_PROGRESS / ((double) mDuration)));
                if (mPlayBar != null && !mPlayBar.isSeeking()) {
                    mPlayBar.setProgress(progress);
                    return;
                }
                return;
            }
            mPlayBar.setProgress(0);
        }
    }

    private void setPlayerBuffering() {
        LogUtil.d(TAG, "setPlayerBuffering isPause=" + isPause);
        if (!isPause) {
            mPlayBar.setState(1);
        }
    }

    private void setPlayerPrePared() {
        mPlayBar.setState(4);
        //mSv.setBackgroundResource(17170445);
        setTotalTime();
        if (!(mUKingPlayerIJKImpl == null || mUKingPlayerIJKImpl.getMediaPlayer() == null)) {
            LogUtil.d(TAG, "setPlayerPrePared--isPlayerError=" + isPlayerError + "----mLastPosition=" + mLastPosition);
            if (isPlayerError && mLastPosition > 0) {
                mUKingPlayerIJKImpl.getMediaPlayer().seekTo(mLastPosition);
            } else if (mRecordLastPlayPosition != 0) {
                mUKingPlayerIJKImpl.getMediaPlayer().seekTo(mRecordLastPlayPosition);
            }
        }
        isPlayerError = false;
        isPause = false;
        isPrepared = true;
    }

    private void setPlayerComplete() {
        if (mErrorDialog != null && mErrorDialog.isShowing()) {
            return;
        }
        if (mStreamingIndex + INVALID_JNI_ERROR_CODE < 0 || mStreamingIndex + INVALID_JNI_ERROR_CODE >= mStreamingModels.size()) {
            finish();
            return;
        }
        mStreamingIndex += INVALID_JNI_ERROR_CODE;
        mPlayBar.setLoadingNext(true);
        mPlayBar.setState(0);
        checkIsNeedPlayContinue();
    }

    private void setPlayerPlaying() {
        LogUtil.d(TAG, "setPlayerPlaying ispause=" + isPause);
        if (!isPause) {
            mPlayBar.setState(3);
            cancelErrorDialog();
        }
    }

    private void play() {
        LogUtil.d(TAG, "hasRecordPlayPosition=false;");
        mPlayBar.removeCallbacks(setCanShowEcErrorRunnable);
        canShowEcError = false;
        hasRecordPlayPosition = false;
        mJinErrorCode = INVALID_JNI_ERROR_CODE;
        mPlayBar.postDelayed(setCanShowEcErrorRunnable, DELAY_SET_CAN_SHOW_EC_ERROR);
        mJinErrorCode = INVALID_JNI_ERROR_CODE;
        if (mStreamingModels != null) {
            StreamInfo streamingModel = (StreamInfo) mStreamingModels.get(mStreamingIndex);
            if (mUKingPlayerIJKImpl == null || TextUtils.isEmpty(streamingModel.getMedia_code())) {
                mPlayBar.setState(-2);
            } else {
                String url = streamingModel.getMedia_code();
                mUKingPlayerIJKImpl.playUrl(url);
                LogUtil.d(TAG, "playurl=" + url);
            }
        } else {
            mPlayBar.setState(-2);
        }
        mPlayBar.setStreamingModel(mVodData, mStreamingIndex);
        mSelectLayout.post(new Runnable() {
            public void run() {
                mSelectLayout.setSelection(mStreamingIndex);
            }
        });
    }

    private void rePlay() {
        play();
    }

    private void init() {
        mUKingPlayerIJKImpl = new UKingPlayerIJKImpl(this, mSv, mUKingPlayerIJKImplHandler, mPlayBar.getSeekBar(), VKJniHander, false);
    }

    private void setPause() {
        if (mUKingPlayerIJKImpl != null && mUKingPlayerIJKImpl.getMediaPlayer() != null) {
            mUKingPlayerIJKImpl.pause();
            isPause = true;
            mPlayBar.setState(2);
            LogUtil.d(TAG, "setPause");
        }
    }

    private void setResume() {
        if (mUKingPlayerIJKImpl != null && mUKingPlayerIJKImpl.getMediaPlayer() != null) {
            mUKingPlayerIJKImpl.resume();
            isPause = false;
            setPlayerPlaying();
            LogUtil.d(TAG, "setResume");
        }
    }

    public void onResume() {
        super.onResume();
        LogUtil.d(TAG, "onResume");
//
//        checkIsNeedPlayContinue();
//        LogUtil.d(TAG, "checkIsNeedPlayContinue");

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        LogUtil.d(TAG, "onKeyDonw=" + keyCode);
        switch (keyCode) {
            case 4 /*4*/:
                if (event.getRepeatCount() == 0) {
                    if (mSelectLayout.getVisibility() == View.VISIBLE) {
                        mSelectLayout.updateVisibility();
                        return true;
                    } else if (mPlayBar.getBottomLayout().getVisibility() == View.VISIBLE) {
                        mPlayBar.getBottomLayout().setVisibility(View.GONE);
                        return true;
                    }
                }
                break;
            case 19 /*19*/:
                if (event.getRepeatCount() == 0 && isPause) {
                    return true;
                }
            case 20 /*20*/:
                if (event.getRepeatCount() == 0 && isPause) {
                    return true;
                }
            case 21 /*21*/:
            case 22 /*22*/:
                LogUtil.d(TAG, "LEFT/RIGHT isPause=" + isPause);
                if (!(mSelectLayout.getVisibility() == View.VISIBLE || mPlayBar.getBottomLayout().getVisibility() == View.VISIBLE)) {
                    mPlayBar.getBottomLayout().setVisibility(View.VISIBLE);
                    mPlayBar.getBottomLayout().setAutoHide(false);
                    break;
                }
            case 23/*23*/:
                if (!(event.getRepeatCount() != 0 || mPlayBar.getState() == 7 || mPlayBar.getState() == 6 || mPlayBar.getState() == 4 || mPlayBar.getState() == 0 || mPlayBar.getState() == INVALID_JNI_ERROR_CODE || mPlayBar.getState() == -3 || mPlayBar.getState() == -2 || mUKingPlayerIJKImpl == null || mUKingPlayerIJKImpl.getMediaPlayer() == null)) {
                    if (!mUKingPlayerIJKImpl.getMediaPlayer().isPlaying()) {
                        setResume();
                        break;
                    }
                    setPause();
                    if (mPlayBar.getBottomLayout().getVisibility() == View.VISIBLE) {
                        mPlayBar.getBottomLayout().delayHide();
                        break;
                    }
                    mPlayBar.updateBottomLayoutVisibility();
                    break;
                }
            case 24 /*24*/:
            case 25 /*25*/:
            case 164:
                break;
            case 82 /*82*/:
                LogUtil.d(TAG, "KEYCODE_MENU");
                if (event.getRepeatCount() == 0) {
                    mSelectLayout.updateVisibility();
                    if (mPlayBar.getBottomLayout().getVisibility() == View.VISIBLE && mSelectLayout.getVisibility() == View.VISIBLE) {
                        mPlayBar.getBottomLayout().setVisibility(View.GONE);
                        break;
                    }
                }
                break;
            default:
                if (event.getRepeatCount() == 0) {
                    mPlayBar.updateBottomLayoutVisibility();
                    break;
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        LogUtil.d(TAG, "onKeyUp");
        return super.onKeyUp(keyCode, event);
    }

    public void onPause() {
        if (!hasRecordPlayPosition) {
            recordPlayPosition();
        }
        super.onPause();
    }

    public void finish() {
        LogUtil.d(TAG, "finish");
        unBindKBPlayerMsgServer();
        if (!hasRecordPlayPosition) {
            recordPlayPosition();
        }
        super.finish();
    }

    private int checkPlayPostion(int duration,int current) {
        if(duration > 1 && current >= duration
                - offsetPlayOption / 2) {
            return 0;
        }else {
            return current;
        }
    }
    private void setLinkPlayfinsh(Links link,int duration,int current) {
        if(duration > 1 && current >= duration
                - offsetPlayOption / 2) {
            link.setIsPalyfinsh(1);
        }else {
            link.setIsPalyfinsh(0);
        }
    }

    // 查询视频的播放记录 返回Link
    //select 当前的剧集标
    public Links getVideoOperation(int select) {
        album = mStreamingDao.queryRecordByTypeAndId(mVodData.getMovie_id()+"_"+Constant.TYPE_JILU, Constant.TYPE_JILU);
        LogUtil.e(TAG, "getVideoOperation albums = "+album);
        if(null != album ){
            try {
                LogUtil.e(TAG, "getVideoOperation album.palyIndex = "+album.getPostiveplayIndex());
                String mediaCode = "";
                if(mVodData.getMedia_type().equals(Constant.SERIES)
                        &&mVodData.getStreaming()!=null
                        &&mVodData.getStreaming().get(select)!=null) {
                    mediaCode = mVodData.getStreaming().get(select).getMedia_code();
                } else {
                    mediaCode = mVodData.getMedia_code();
                }
                LogUtil.e(TAG, "getVideoOperation mVodData.getStreaming().get(select).getMeidiaCode() = " + mediaCode);
                List<Links> links = mStreamingDao.queryLinkById(mediaCode);
                if (null != links && links.size() > 0) {
                    Links link = links.get(0);
                    return link;
                }

            } catch (Exception e) {
                // TODO: handle exception
                LogUtil.e(TAG, "getVideoOperation ....has Exception = "+e.getLocalizedMessage());
            }
        }
        return null;
    }
    // 设置视频的播放记录
    //select 当前的剧集标
    public void setVideoOperation(int select,int currPosition) {
        album = mStreamingDao.queryRecordByTypeAndId(mVodData.getMovie_id()+"_"+Constant.TYPE_JILU, Constant.TYPE_JILU);
        if(null!=album){
            try {
                String MediaCode = "";
                if(mVodData.getMedia_type().equals(Constant.SERIES)
                        &&mVodData.getStreaming()!=null
                        &&mVodData.getStreaming().get(select)!=null) {
                    String meidiaName=mVodData.getStreaming().get(select).getSubtitle();
                    album.setPlayIndexTitle(meidiaName);
                    album.setStreamNumber(mVodData.getStreaming().size());
                    MediaCode = mVodData.getStreaming().get(select).getMedia_code();
                } else {
                    album.setPlayIndexTitle("");
                    MediaCode = mVodData.getMedia_code();
                }
                List<Links> links = mStreamingDao.queryLinkById(MediaCode);
                if(null != links && links.size()>0){
                    Links link = links.get(0);
                    setLinkPlayfinsh(link, mDuration, currPosition);
                    int Position = checkPlayPostion(mDuration, currPosition);
                    link.setRecordTime(Position);
                    link.setContentId(MediaCode);
                    mStreamingDao.addLinks(link);
                }else {
                    Links vinfo = new Links();
                    vinfo.setContentId(MediaCode);
                    vinfo.setMeidiaName(mVodData.getStreaming().get(select).getSubtitle());
                    vinfo.setShort_title(mVodData.getStreaming().get(select).getSubtitle());
                    setLinkPlayfinsh(vinfo, mDuration, currPosition);
                    int Position = checkPlayPostion(mDuration, currPosition);
                    vinfo.setRecordTime(Position);
                    mStreamingDao.addLinks(vinfo);
                }
                album.setTime(Utils.getSystemTime());
                album.setCategory_id(mVodData.getCategory_id());
                mStreamingDao.addRecords(album);
                //				LogUtil.e(TAG, "setVideoOperation album.tostring() = "+album.toString());
            } catch (Exception e) {
                // TODO: handle exception
                LogUtil.e(TAG, "setVideoOperation ....has Exception = "+e.getLocalizedMessage());
            }
        }

    }
    // 保存 视频播放进度
    private void restoreElapseMsec(MovieDetail vod,int mplayerCurPostin) {
//				int currPosition = mPlayer.getMediaPlayer().getCurrentPosition();
        // 此位置存在1，2s内的误差（seekTo同样也会产生很大的误差），可以解决缓存时无历史记录的问题
        int currPosition = mplayerCurPostin;
        if (currPosition >= 1000) {
            String vodId = vod.getMedia_code();
            Record albums = mStreamingDao.queryRecordByTypeAndId(vod.getMovie_id()+"_"+Constant.TYPE_JILU, Constant.TYPE_JILU);// 查询视频记录
            if (albums == null) {
                Record al = new Record();
                al.setMovie_id(vod.getMovie_id()+"_" + Constant.TYPE_JILU);
                if(!vod.getMedia_type().equals(Constant.SERIES)) {
                    al.setPlayIndexTitle("");
                    Links vinfo = new Links();
                    vinfo.setContentId(vod.getMedia_code());
                    vinfo.setMeidiaName(vod.getSubtitle());
                    vinfo.setShort_title(vod.getSubtitle());
                    setLinkPlayfinsh(vinfo, mDuration, currPosition);
                    currPosition = checkPlayPostion(mDuration, currPosition);
                    vinfo.setRecordTime(currPosition);
                    mStreamingDao.addLinks(vinfo);
                }else if(vod.getStreaming()!=null
                        &&vod.getStreaming().size()>0
                        &&mStreamingIndex<vod.getStreaming().size()){
                    al.setStreamNumber(mVodData.getStreaming().size());
                    Links vinfo = new Links();
                    vinfo.setContentId(vod.getStreaming().get(mStreamingIndex).getMedia_code());
                    vinfo.setMeidiaName(vod.getStreaming().get(mStreamingIndex).getSubtitle());
                    vinfo.setShort_title(vod.getStreaming().get(mStreamingIndex).getSubtitle());
                    setLinkPlayfinsh(vinfo, mDuration, currPosition);
                    currPosition = checkPlayPostion(mDuration, currPosition);
                    vinfo.setRecordTime(currPosition);
                    mStreamingDao.addLinks(vinfo);
                } else {
                    al.setPlayIndexTitle("");
                }
                al.setDecplayIndex(mStreamingIndex);
                al.setPostiveplayIndex(mStreamingIndex);
                al.setAlbumType(vod.getSubtitle());
                al.setTypeId(Constant.TYPE_JILU);
                al.setMedia_code(vodId);
                al.setAlbumPic(Utils.getPosterUrl(vod));
                al.setCategory_id(vod.getCategory_id());
                al.setTime(Utils.getSystemTime());
                mStreamingDao.addRecords(al);               // 添加视频记录
                LogUtil.e(TAG, "dao.addAlbums(al)....... ");
//						getVideoOperation(playIndex);
            }else{                                             // 保存电视剧播放到的集数
                setVideoOperation(mStreamingIndex,currPosition);
                LogUtil.e(TAG, "setVideoOperation....... mplayerCurPostin="+mplayerCurPostin);
//						getVideoOperation(playIndex).getRecordTime();
            }
        }else {
            LogUtil.i(TAG, "save Current mPlayer Postion less than 1 s !");
        }
    }
    private void recordPlayPosition() {
        LogUtil.d(TAG, "recordPlayPosition");
        if (!(mUKingPlayerIJKImpl == null || mUKingPlayerIJKImpl.getMediaPlayer() == null || !isPrepared)) {
            int position = (int)mUKingPlayerIJKImpl.getMediaPlayer().getCurrentPosition();
            LogUtil.d(TAG, "position=" + position);
            if (position > 0) {
                restoreElapseMsec(mVodData,position);
            }
        }
        hasRecordPlayPosition = true;
    }

    private void clearPlayPosition() {
        LogUtil.d(TAG, "clearPlayPosition");
        setVideoOperation(mStreamingIndex, 0);
        mLastPosition = 0;
        hasRecordPlayPosition = true;
    }

    private void startPlayContinueCountDownTimer() {
        mPlayContinueCountDownTimer = new PlayContinueCountDownTimer(PLAY_CONTINUE_COUNT_DOWN_TIME, PLAY_CONTINUE_COUNT_DOWN_INTERVAL);
        mPlayContinueCountDownTimer.start();
    }

    private void checkIsNeedPlayContinue() {
        if(mStreamingModels!=null&&mStreamingModels.size()>0) {
            LogUtil.d(TAG, "checkIsNeedPlayContinue streaming_code=" + ((StreamInfo) mStreamingModels.get(mStreamingIndex)).getMedia_code());
            Links recordInfo = getVideoOperation(mStreamingIndex);
            if (recordInfo != null) {
                LogUtil.d(TAG, "checkIsNeedPlayContinue model=" + recordInfo);
                mRecordLastPlayPosition = recordInfo.getRecordTime();
                if (mRecordLastPlayPosition > MS_TO_S) {
                    LogUtil.d(TAG, "checkIsNeedPlayContinue=" + mRecordLastPlayPosition);
                    showPlayContinueDialog();
                    startPlayContinueCountDownTimer();
                }
            } else {
                LogUtil.d(TAG, "checkIsNeedPlayContinue=null");
                play();
            }

        }
    }

    private void cancelPlayContinueDialog() {
        if (mPlayContinueDialog != null && mPlayContinueDialog.isShowing()) {
            mPlayContinueDialog.dismiss();
            mPlayContinueDialog.cancel();
            mPlayContinueDialog = null;
        }
    }

    private void showPlayContinueDialog() {
        cancelPlayContinueDialog();
        if (mPlayContinueDialog == null) {
            mPlayContinueDialog = new BaseDialog(this);
        }
        String hint = getString(R.string.play_last_time) + DateUtil.showTime((long) (mRecordLastPlayPosition / MS_TO_S));
        mPlayContinueDialog.setMessage(hint);
        mPlayContinueBtn = mPlayContinueDialog.setNegativeButton(hint, new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                setRecordContinuePlay();
                cancelPlayContinueDialog();
                play();
            }
        });
        mPlayContinueDialog.setPositiveButton(getString(R.string.play_form_begin), new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                setRecordRePlay();
                cancelPlayContinueDialog();
                mRecordLastPlayPosition = 0;
                play();
            }
        });
        mPlayContinueDialog.show();
        mPlayContinueBtn.requestFocus();
    }

    private void setRecordRePlay() {
        mRecordLastPlayPosition = 0;
    }

    private void setRecordContinuePlay() {
//        if (mUKingPlayerIJKImpl != null && mUKingPlayerIJKImpl.getMediaPlayer() != null && mUKingPlayerIJKImpl.getMediaPlayer().isPlaying() && mRecordLastPlayPosition != 0) {
//            mUKingPlayerIJKImpl.getMediaPlayer().seekTo(mRecordLastPlayPosition);
//        }
    }

    private void startCheckPlaying() {
        if (mUKingPlayerIJKImpl != null && mUKingPlayerIJKImpl.getMediaPlayer() != null) {
            mCheckPlayerIsPlayingHandler.removeCallbacks(mCheckPlayerIsPlayingRunnable);
            beginCheckPosition = (int)mUKingPlayerIJKImpl.getMediaPlayer().getCurrentPosition() / MS_TO_S;
            mCheckPlayerIsPlayingHandler.postDelayed(mCheckPlayerIsPlayingRunnable, DELAY_CHECK_ISPLAYING);
        }
    }

    protected void onErrorToastDialogCancel(String msg) {
        super.onErrorToastDialogCancel(msg);
        if (mCheckPlayerIsPlayingHandler != null && mCheckPlayerIsPlayingRunnable != null) {
            mCheckPlayerIsPlayingHandler.removeCallbacks(mCheckPlayerIsPlayingRunnable);
            mLastSetTime = SystemClock.uptimeMillis();
        }
    }

    protected int getPort() {
        return 9998;
    }

    protected void bindKBPlayerMsgServer() {
        isBound=bindService(new Intent(this, UKingPlayerMessageService.class), this.connection, Context.BIND_AUTO_CREATE);
    }

    protected void unBindKBPlayerMsgServer() {
        if (this.connection != null&&isBound) {
            unbindService(this.connection);
            connection = null;
            this.isBound = false;
        }
    }
}
